package cn.glinks.liuhe.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.glinks.liuhe.R;
import cn.glinks.liuhe.api.jsonbean.ParksInfo;
import cn.glinks.liuhe.app.AppApplication;
import cn.glinks.liuhe.app.AppConstant;
import cn.glinks.liuhe.base.BaseActivity;
import cn.glinks.liuhe.utils.ActTransAnimUtils;
import cn.glinks.liuhe.utils.DisplayUtils;
import cn.glinks.liuhe.utils.ToastUtils;


/**
 * Des:统计图表页面2
 *
 * @author MarsBlade of Cyh
 * @created 2017-03-21 14:43
 */
public class ChartTwoActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView mTitleText;

    @BindView(R.id.tv_sum)
    TextView mSumText;

    @BindView(R.id.view_piechart_in)
    PieChart mPieChartIn;

    @BindView(R.id.view_piechart_out)
    PieChart mPieChartOut;

    @BindView(R.id.tv_male_20)
    TextView mMale1Text;

    @BindView(R.id.tv_male_21_25)
    TextView mMale2Text;

    @BindView(R.id.tv_male_26_30)
    TextView mMale3Text;

    @BindView(R.id.tv_male_31_35)
    TextView mMale4Text;

    @BindView(R.id.tv_male_36_40)
    TextView mMale5Text;

    @BindView(R.id.tv_male_41)
    TextView mMale6Text;

    @BindView(R.id.tv_female_20)
    TextView mFemale1Text;

    @BindView(R.id.tv_female_21_25)
    TextView mFemale2Text;

    @BindView(R.id.tv_female_26_30)
    TextView mFemale3Text;

    @BindView(R.id.tv_female_31_35)
    TextView mFemale4Text;

    @BindView(R.id.tv_female_36_40)
    TextView mFemale5Text;

    @BindView(R.id.tv_female_41)
    TextView mFemale6Text;

    // 变量
    private int mIndex = -1;
    private String mLevelName = "";
    private ParksInfo mParksInfo = null;
    private ParksInfo.ParksBean mParksBean = null;
    private PieData mPieOutData = null;
    private PieData mPieInData = null;

    // 图表数据
    private int male_20 = 0;
    private int male_21_25 = 0;
    private int male_26_30 = 0;
    private int male_31_35 = 0;
    private int male_36_40 = 0;
    private int male_41 = 0;
    private int male_sum = 0;
    private int female_20 = 0;
    private int female_21_25 = 0;
    private int female_26_30 = 0;
    private int female_31_35 = 0;
    private int female_36_40 = 0;
    private int female_41 = 0;
    private int female_sum = 0;
    private int sum = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_chart_2;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        // 获取传递过来的数据
        Bundle bundle = this.getIntent().getExtras();
        mIndex = bundle.getInt(AppConstant.BUNDLE_PARK_INDEX, -1);
        mLevelName = bundle.getString(AppConstant.BUNDLE_PARK_LEVEL_NAME, "");
        // 获取园区统计数据
        mParksInfo = ((AppApplication) getApplicationContext()).getStatisticData();
        if (mIndex >= 0) {
            mParksBean = mParksInfo.getParks().get(mIndex);
            if (initDatas(mLevelName)) {
                showLabelDatas();
            } else {
                ToastUtils.showShort("加载年龄区间数据失败");
            }
        } else {
            ToastUtils.showShort("加载数据失败");
        }
        // 加载数据
        mPieOutData = getChartOutData();
        mPieInData = getChartInData();
        // 旋转Root View(横屏处理)
        RelativeLayout rootLayout = (RelativeLayout)findViewById(R.id.rl_chart_1_root);
        int screenHeight = DisplayUtils.getScreenHeight(this);
        int screenWidth = DisplayUtils.getScreenWidth(this);
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) rootLayout.getLayoutParams();
        params.height = screenWidth;
        params.width = screenHeight;
        params.topMargin = (screenHeight - screenWidth) / 2;
        params.leftMargin = (screenWidth - screenHeight) / 2;
        rootLayout.setLayoutParams(params);
        rootLayout.setRotation(90);
        // 设置为透明状态栏
        SetTranslanteBar();
        // 设置标题
        mTitleText.setText(mLevelName+"员工性别分布");
        mSumText.setText(sum+"人");
        // 初始化饼状图View
        initChartOutView();
        initChartInView();
    }

    /*--------------------------------------------------------------------------------
     *                          数据初始化函数
     ---------------------------------------------------------------------------------*/
    private boolean initDatas(String levelName) {
        if (levelName.equals("合格")) {
            male_20 = mParksBean.getL3().get(0);
            male_21_25 = mParksBean.getL3().get(1);
            male_26_30 = mParksBean.getL3().get(2);
            male_31_35 = mParksBean.getL3().get(3);
            male_36_40 = mParksBean.getL3().get(4);
            male_41 = mParksBean.getL3().get(5);
            male_sum = male_20 + male_21_25 + male_26_30 + male_31_35 + male_36_40 + male_41;
            female_20 = mParksBean.getL3().get(6);
            female_21_25 = mParksBean.getL3().get(7);
            female_26_30 = mParksBean.getL3().get(8);
            female_31_35 = mParksBean.getL3().get(9);
            female_36_40 = mParksBean.getL3().get(10);
            female_41 = mParksBean.getL3().get(11);
            female_sum = female_20 + female_21_25 + female_26_30 + female_31_35 + female_36_40 + female_41;
            sum = male_sum + female_sum;
            return true;
        } else if (levelName.equals("可疑")) {
            male_20 = mParksBean.getL4().get(0);
            male_21_25 = mParksBean.getL4().get(1);
            male_26_30 = mParksBean.getL4().get(2);
            male_31_35 = mParksBean.getL4().get(3);
            male_36_40 = mParksBean.getL4().get(4);
            male_41 = mParksBean.getL4().get(5);
            male_sum = male_20 + male_21_25 + male_26_30 + male_31_35 + male_36_40 + male_41;
            female_20 = mParksBean.getL4().get(6);
            female_21_25 = mParksBean.getL4().get(7);
            female_26_30 = mParksBean.getL4().get(8);
            female_31_35 = mParksBean.getL4().get(9);
            female_36_40 = mParksBean.getL4().get(10);
            female_41 = mParksBean.getL4().get(11);
            female_sum = female_20 + female_21_25 + female_26_30 + female_31_35 + female_36_40 + female_41;
            sum = male_sum + female_sum;
            return true;
        } else if (levelName.equals("关注")) {
            male_20 = mParksBean.getL2().get(0);
            male_21_25 = mParksBean.getL2().get(1);
            male_26_30 = mParksBean.getL2().get(2);
            male_31_35 = mParksBean.getL2().get(3);
            male_36_40 = mParksBean.getL2().get(4);
            male_41 = mParksBean.getL2().get(5);
            male_sum = male_20 + male_21_25 + male_26_30 + male_31_35 + male_36_40 + male_41;
            female_20 = mParksBean.getL2().get(6);
            female_21_25 = mParksBean.getL2().get(7);
            female_26_30 = mParksBean.getL2().get(8);
            female_31_35 = mParksBean.getL2().get(9);
            female_36_40 = mParksBean.getL2().get(10);
            female_41 = mParksBean.getL2().get(11);
            female_sum = female_20 + female_21_25 + female_26_30 + female_31_35 + female_36_40 + female_41;
            sum = male_sum + female_sum;
            return true;
        } else if (levelName.equals("不合格")) {
            male_20 = mParksBean.getL1().get(0);
            male_21_25 = mParksBean.getL1().get(1);
            male_26_30 = mParksBean.getL1().get(2);
            male_31_35 = mParksBean.getL1().get(3);
            male_36_40 = mParksBean.getL1().get(4);
            male_41 = mParksBean.getL1().get(5);
            male_sum = male_20 + male_21_25 + male_26_30 + male_31_35 + male_36_40 + male_41;
            female_20 = mParksBean.getL1().get(6);
            female_21_25 = mParksBean.getL1().get(7);
            female_26_30 = mParksBean.getL1().get(8);
            female_31_35 = mParksBean.getL1().get(9);
            female_36_40 = mParksBean.getL1().get(10);
            female_41 = mParksBean.getL1().get(11);
            female_sum = female_20 + female_21_25 + female_26_30 + female_31_35 + female_36_40 + female_41;
            sum = male_sum + female_sum;
            return true;
        } else if (levelName.equals("无效")) {
            male_20 = mParksBean.getL5().get(0);
            male_21_25 = mParksBean.getL5().get(1);
            male_26_30 = mParksBean.getL5().get(2);
            male_31_35 = mParksBean.getL5().get(3);
            male_36_40 = mParksBean.getL5().get(4);
            male_41 = mParksBean.getL5().get(5);
            male_sum = male_20 + male_21_25 + male_26_30 + male_31_35 + male_36_40 + male_41;
            female_20 = mParksBean.getL5().get(6);
            female_21_25 = mParksBean.getL5().get(7);
            female_26_30 = mParksBean.getL5().get(8);
            female_31_35 = mParksBean.getL5().get(9);
            female_36_40 = mParksBean.getL5().get(10);
            female_41 = mParksBean.getL5().get(11);
            female_sum = female_20 + female_21_25 + female_26_30 + female_31_35 + female_36_40 + female_41;
            sum = male_sum + female_sum;
            return true;
        } else {
            return false;
        }

    }

    private void showLabelDatas() {
        // 避免除数为空的错误
        int male_sum_tmp = male_sum;
        int female_sum_tmp = female_sum;
        if (male_sum_tmp <= 0) {
            male_sum_tmp = 1;
        }
        if (female_sum_tmp <= 0) {
            female_sum_tmp = 1;
        }


        mMale1Text.setText("("+String.format("%.1f", male_20*100.0f/male_sum_tmp)+"%,"+male_20+"人)");
        mMale2Text.setText("("+String.format("%.1f", male_21_25*100.0f/male_sum_tmp)+"%,"+male_21_25+"人)");
        mMale3Text.setText("("+String.format("%.1f", male_26_30*100.0f/male_sum_tmp)+"%,"+male_26_30+"人)");
        mMale4Text.setText("("+String.format("%.1f", male_31_35*100.0f/male_sum_tmp)+"%,"+male_31_35+"人)");
        mMale5Text.setText("("+String.format("%.1f", male_36_40*100.0f/male_sum_tmp)+"%,"+male_36_40+"人)");
        mMale6Text.setText("("+String.format("%.1f", male_41*100.0f/male_sum_tmp)+"%,"+male_41+"人)");
        mFemale1Text.setText("("+female_20+"人,"+String.format("%.1f", female_20*100.0f/female_sum_tmp)+"%)");
        mFemale2Text.setText("("+female_21_25+"人,"+String.format("%.1f", female_21_25*100.0f/female_sum_tmp)+"%)");
        mFemale3Text.setText("("+female_26_30+"人,"+String.format("%.1f", female_26_30*100.0f/female_sum_tmp)+"%)");
        mFemale4Text.setText("("+female_31_35+"人,"+String.format("%.1f", female_31_35*100.0f/female_sum_tmp)+"%)");
        mFemale5Text.setText("("+female_36_40+"人,"+String.format("%.1f", female_36_40*100.0f/female_sum_tmp)+"%)");
        mFemale6Text.setText("("+female_41+"人,"+String.format("%.1f", female_41*100.0f/female_sum_tmp)+"%)");
    }

    /*--------------------------------------------------------------------------------
     *                          饼状图初始化函数
     ---------------------------------------------------------------------------------*/
    /**
     * 构建PieData数据(外环)
     */
    private PieData getChartOutData() {
        List<PieEntry> list = new ArrayList<>();
        ArrayList<Integer> colors = new ArrayList<>();
        // 加载数据
        if (male_41 > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_male_41));
            list.add(new PieEntry(male_41, male_41+"人"));
        }
        if (male_36_40 > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_male_36_40));
            list.add(new PieEntry(male_36_40, male_36_40+"人"));
        }
        if (male_31_35 > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_male_31_35));
            list.add(new PieEntry(male_31_35, male_31_35+"人"));
        }
        if (male_26_30 > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_male_26_30));
            list.add(new PieEntry(male_26_30, male_26_30+"人"));
        }
        if (male_21_25 > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_male_21_25));
            list.add(new PieEntry(male_21_25, male_21_25+"人"));
        }
        if (male_20 > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_male_20));
            list.add(new PieEntry(male_20, male_20+"人"));
        }
        if (female_20 > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_female_20));
            list.add(new PieEntry(female_20, female_20+"人"));
        }
        if (female_21_25 > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_female_21_25));
            list.add(new PieEntry(female_21_25, female_21_25+"人"));
        }
        if (female_26_30 > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_female_26_30));
            list.add(new PieEntry(female_26_30, female_26_30+"人"));
        }
        if (female_31_35 > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_female_31_35));
            list.add(new PieEntry(female_31_35, female_31_35+"人"));
        }
        if (female_36_40 > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_female_36_40));
            list.add(new PieEntry(female_36_40, female_36_40+"人"));
        }
        if (female_41 > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_female_41));
            list.add(new PieEntry(female_41, female_41+"人"));
        }
        // 设置PieDataSet
        PieDataSet dataSet = new PieDataSet(list, "男女占比");
        dataSet.setSliceSpace(0f);// 设置扇形间隔
        dataSet.setSelectionShift(0f);// 设置选中扇形的突出显示偏移量
        dataSet.setDrawValues(false);// 设置是否显示y-values(即百分比)
        dataSet.setColors(colors);// 设置饼状图颜色序列
        // 设置PieData
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColors(colors);

        return data;
    }

    /**
     * 初始化饼状图View(外环)
     */
    private void initChartOutView() {
        // 初始化图表
        mPieChartOut.setUsePercentValues(true);//设置显示成比例
        mPieChartOut.getDescription().setEnabled(false);
        mPieChartOut.setDragDecelerationFrictionCoef(0.95f);
        mPieChartOut.setExtraOffsets(0.0f, 0.0f, 0.0f, 0.0f);

        mPieChartOut.setRotationAngle(90);//初始旋转角度
        mPieChartOut.setEntryLabelTextSize(10);//设置 Entry Label 的字体大小(dp)
        mPieChartOut.setRotationEnabled(false);//是否使能手动旋转
        mPieChartOut.setDrawCenterText(false);//饼状图中间是否可以添加文字

        mPieChartOut.setDrawHoleEnabled(true);//是否显示成圆环模式(即带有中心圆的环形图表)
        mPieChartOut.setHoleColor(Color.TRANSPARENT);//中心圆的背景颜色
        mPieChartOut.setHoleRadius(65f);//中心圆的半径(百分比)

        mPieChartOut.setTransparentCircleColor(Color.WHITE);//半透明圆环的颜色
        mPieChartOut.setTransparentCircleAlpha(110);//半透明圆环的透明度
        mPieChartOut.setTransparentCircleRadius(70f);//半透明圆环的半径(百分比),一般比中心圆半径多5f


        mPieChartOut.setHighlightPerTapEnabled(true);

        // add a selection listener
        mPieChartOut.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
            }

            @Override
            public void onNothingSelected() {
            }
        });

        mPieChartOut.setData(mPieOutData);

        // undo all highlights
        mPieChartOut.highlightValues(null);

        mPieChartOut.invalidate();

        mPieChartOut.animateY(1400, Easing.EasingOption.EaseInOutQuad);
        // mPieChartOut.spin(2000, 0, 360);

        //设置比例图
        Legend legend = mPieChartOut.getLegend();
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        legend.setOrientation(Legend.LegendOrientation.VERTICAL);
        legend.setDrawInside(false);
        legend.setEnabled(false);//设置禁用比例块
    }

    /**
     * 构建PieData数据(内环)
     */
    private PieData getChartInData() {
        List<PieEntry> list = new ArrayList<>();
        ArrayList<Integer> colors = new ArrayList<Integer>();
        // 加载数据
        float male_rate = male_sum * 100.0f / sum;
        float female_rate = 100.0f - male_rate;
        if (male_rate > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_male_20));
            list.add(new PieEntry(male_rate, (int)male_rate+"%"));
        }
        if (female_rate > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_female_20));
            list.add(new PieEntry(female_rate, (int)female_rate+"%"));
        }
        // 设置PieDataSet
        PieDataSet dataSet = new PieDataSet(list, "男女占比");
        dataSet.setSliceSpace(0f);// 设置扇形间隔
        dataSet.setSelectionShift(0f);// 设置选中扇形的突出显示偏移量
        dataSet.setDrawValues(false);// 设置是否显示y-values(即百分比)
        dataSet.setColors(colors);// 设置饼状图颜色序列
        // 设置PieData
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColors(colors);

        return data;
    }

    /**
     * 初始化饼状图View(内环)
     */
    private void initChartInView() {
        // 初始化图表
        mPieChartIn.setUsePercentValues(true);//设置显示成比例
        mPieChartIn.getDescription().setEnabled(false);
        mPieChartIn.setExtraOffsets(0.0f, 0.0f, 0.0f, 0.0f);
        mPieChartIn.setDragDecelerationFrictionCoef(0.95f);

        mPieChartIn.setRotationAngle(90);//初始旋转角度
        mPieChartIn.setEntryLabelTextSize(10);//设置 Entry Label 的字体大小(dp)
        mPieChartIn.setRotationEnabled(false);//是否使能手动旋转
        mPieChartIn.setDrawCenterText(false);//饼状图中间是否可以添加文字
        mPieChartIn.setDrawSlicesUnderHole(false);

        mPieChartIn.setDrawHoleEnabled(true);//是否显示成圆环模式(即带有中心圆的环形图表)
        mPieChartIn.setHoleColor(Color.TRANSPARENT);//中心圆的背景颜色
        mPieChartIn.setHoleRadius(45f);//中心圆的半径(百分比)

        mPieChartIn.setTransparentCircleColor(Color.WHITE);//半透明圆环的颜色
        mPieChartIn.setTransparentCircleAlpha(110);//半透明圆环的透明度
        mPieChartIn.setTransparentCircleRadius(50f);//半透明圆环的半径(百分比),一般比中心圆半径多5f



        mPieChartIn.setHighlightPerTapEnabled(true);

        // add a selection listener
        mPieChartIn.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
            }

            @Override
            public void onNothingSelected() {
            }
        });

        mPieChartIn.setData(mPieInData);

        // undo all highlights
        mPieChartIn.highlightValues(null);

        mPieChartIn.invalidate();

        mPieChartIn.animateY(1400, Easing.EasingOption.EaseInOutQuad);
        // mPieChartIn.spin(2000, 0, 360);

        //设置比例图
        Legend legend = mPieChartIn.getLegend();
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        legend.setOrientation(Legend.LegendOrientation.VERTICAL);
        legend.setDrawInside(false);
        legend.setEnabled(false);//设置禁用比例块
    }

    /*--------------------------------------------------------------------------------
     *                          点击事件接口实现
     ---------------------------------------------------------------------------------*/
    // 返回
    @OnClick(R.id.iv_cancel)
    public void clickCancel() {
        // 返回
        ActTransAnimUtils.finishActionFadeOut(this);
    }

    // 左按键
    @OnClick(R.id.tv_left)
    public void clickLeft() {
        // 打包数据,传递并跳转到搜索页面
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.BUNDLE_PARK_NAME, mParksBean.getParkName());
        ActTransAnimUtils.startActionSlideRightToLeft(this, SearchActivity.class, bundle);
    }

    // 右按键
    @OnClick(R.id.tv_right)
    public void clickRight() {
        // 返回
        ActTransAnimUtils.finishActionFadeOut(this);
    }

    /*--------------------------------------------------------------------------------
     *                          系统键处理
     ---------------------------------------------------------------------------------*/
    /**
     * 监听主页键,返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 返回
            ActTransAnimUtils.finishActionFadeOut(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
